package com.moorecat.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.bean.Shop;
import com.moorecat.bean.SignInfo;
import com.moorecat.exception.SVException;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.ui.ProgressLinearLayout;
import com.moorecat.utils.ui.UiUtils;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-12 上午07:49:38 类说明
 */
public class BusinessSignin extends Activity implements OnClickListener {

	private static final String TAG = "BusienssSignin";

	private ImageView signin;

	private ListView listView;

	private TextView businessName, businessAddress;

	private ProgressLinearLayout footer;

	private SigninAdapter adapter;

	private MooerApplication mooerApp;

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

	private Shop businessInfo;

	private long taskId;

	private boolean isCancelled, isSigning;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.business_signin);
		Intent intent = getIntent();
		businessInfo = (Shop) intent.getSerializableExtra("businessInfo");
		mooerApp = (MooerApplication) getApplication();
		signin = (ImageView) findViewById(R.id.signin);
		listView = (ListView) findViewById(R.id.listview);
		businessName = (TextView) findViewById(R.id.business_name);
		businessAddress = (TextView) findViewById(R.id.business_address);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		adapter = new SigninAdapter();
		listView.setAdapter(adapter);
		signin.setOnClickListener(this);
		businessName.setText(Business.businessInfo.getName());
		businessAddress.setText(getString(R.string.address, businessInfo
				.getAddress().getAddress1()));
		footer.setOnClickListener(this);
		new AllSignTask().execute(businessInfo.getId());
	}

	@Override
	public void onClick(View v) {
		if (v == signin) {
			if (mooerApp.isLoggedin()) {
				if (isSigning) {
					UiUtils.showToast(this, "正在签到，请稍候");
					return;
				}
				isSigning = true;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("shopId", businessInfo.getId());
				map.put("userId", mooerApp.getUser().getId());
				map.put("longitude", mooerApp.getLongitude());
				map.put("latitude", mooerApp.getLatitude());
				map.put("content", "");
				new SignTask().execute(map);
			} else {
				Intent intent = new Intent(this, MoreAccountSetting.class);
				intent.putExtra("isFinish", true);
				startActivityForResult(intent, 0);
			}
		} else if (v == footer.reload) {
			listView.addFooterView(footer);
			footer.setVisibility(View.VISIBLE, View.VISIBLE, View.GONE,
					View.GONE);
			new AllSignTask().execute(businessInfo.getId());
		}

	}

	public class SigninAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View paramView,
				ViewGroup paramViewGroup) {
			LinearLayout itemView = (LinearLayout) LayoutInflater.from(
					BusinessSignin.this).inflate(R.layout.business_signin_item,
					null);
			ImageView pic = (ImageView) itemView.findViewById(R.id.icon);
			ImageView signin = (ImageView) itemView.findViewById(R.id.signin);
			TextView name = (TextView) itemView.findViewById(R.id.name);
			TextView time = (TextView) itemView.findViewById(R.id.time);
			name.setText((String) list.get(position).get("name"));
			time.setText((String) list.get(position).get("time"));
			pic.setImageBitmap((Bitmap) list.get(position).get("icon"));
			signin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View paramView) {
					Intent intent = new Intent(BusinessSignin.this, Sign.class);
					intent.putExtra("tab", "me");
					startActivity(intent);

				}
			});
			itemView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(BusinessSignin.this, Sign.class);
					intent.putExtra("tab", "me");
					startActivity(intent);

				}
			});
			return itemView;
		}
	}

	private class AllSignTask extends
			AsyncTask<Integer, Integer, List<SignInfo>> {

		private boolean isException;

		@Override
		protected List<SignInfo> doInBackground(Integer... params) {
			List<SignInfo> list = null;
			try {
				list = HttpUtils.fetchSignInfoListByShop(params[0], 0, 10);
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<SignInfo> result) {
			super.onPostExecute(result);
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					for (SignInfo signInfo : result) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("name", signInfo.getUser().getUserName());
						map.put("time", signInfo.getDate() + " 签到");
						map.put("icon", mooerApp.getAvatarIcon());
						map.put("picPath", signInfo.getUser().getPhoto());
						list.add(map);
					}
					listView.removeFooterView(footer);
					adapter.notifyDataSetChanged();
					new BitmapTask().execute("");
				} else {
					footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
							View.GONE);
					footer.setText(null, "暂无签到信息");
				}
			}

		}

	}

	private class SignTask extends
			AsyncTask<Map<String, Object>, Integer, String> {

		private boolean isException;

		@Override
		protected String doInBackground(Map<String, Object>... params) {
			Map<String, Object> map = params[0];
			try {
				return HttpUtils.doSignShop((Integer) map.get("shopId"),
						(Integer) map.get("userId"),
						(Double) map.get("longitude"),
						(Double) map.get("latitude"),
						(String) map.get("content"));
			} catch (SVException e) {
				isException = true;
				Log.e(TAG, "", e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			isSigning = false;
			if (isException) {
				UiUtils.showToast(BusinessSignin.this, "签到失败");
			} else {
				UiUtils.showToast(BusinessSignin.this, result);
				list.clear();
				adapter.notifyDataSetChanged();
				listView.addFooterView(footer);
				new AllSignTask().execute(businessInfo.getId());
			}
		}

	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<Map<String, Object>> cacheList = new ArrayList<Map<String, Object>>();
			cacheList.addAll(list);
			Iterator<Map<String, Object>> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId || isCancelled) {
					break;
				}
				Map<String, Object> map = it.next();
				Bitmap icon = null;
				try {
					if (map.get("icon") == mooerApp.getAvatarIcon()) {
						icon = HttpUtils.downloadBitmap((String) map
								.get("picPath"));
						if (icon != null) {
							map.put("icon", icon);
							publishProgress(0);
						}
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isCancelled = true;
	}

}
